<template>
  <div class="production-plan-container">
    <!-- 顶部标题和操作区域 -->
    <div class="top-section">
      <div class="title-area">
        <h2>生产计划</h2>
      </div>
      <div class="search-area">
        <el-form :model="queryForm" inline>
          <el-form-item label="单据编号">
            <el-input
              v-model="queryForm.planNo"
              placeholder="单据编号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :icon="Search">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action-area">
        <el-button type="success" @click="handleNew" :icon="Plus">
          新建
        </el-button>
        <el-button type="primary" @click="handleEdit" :icon="Edit">
          编辑
        </el-button>
        <el-button type="warning" @click="handlePrint" :icon="Printer">
          打印
        </el-button>
        <el-button type="warning" @click="handleExportTemplate" :icon="Document">
          模版Excel导出
        </el-button>
        <el-button type="danger" @click="handleDelete" :icon="Delete">
          删除
        </el-button>
        <el-button type="success" @click="handleExport" :icon="Download">
          导出
        </el-button>
        <el-button @click="handleColumnSettings" :icon="GridIcon">
          列设置
        </el-button>
      </div>
    </div>

    <!-- 生产计划表格 -->
    <div class="table-section">
      <div class="table-container">
        <el-table
          :data="productionPlanList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          :row-class-name="getRowClassName"
          border
          stripe
          style="width: 100%"
          height="300"
        >
                     <el-table-column type="selection" width="55" />
           <el-table-column type="index" label="序号" width="60" align="center" />
           <el-table-column
             v-for="column in visibleColumns"
             :key="column.prop"
             :prop="column.prop"
             :label="column.label"
             :width="column.width"
             :sortable="column.sortable"
             :show-overflow-tooltip="true"
             align="center"
           >
             <template #default="scope">
               <span v-if="column.prop === 'planNo'" class="plan-no-link">
                 {{ scope.row[column.prop] }}
               </span>
               <span v-else-if="column.prop === 'createTime' || column.prop === 'modifyTime'">
                 {{ formatDateTime(scope.row[column.prop]) }}
               </span>
               <span v-else>{{ scope.row[column.prop] || '-' }}</span>
             </template>
           </el-table-column>
           
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 产品明细标题 -->
    <div class="detail-header">
      <h3>生产计划-产品明细</h3>
    </div>

    <!-- 产品明细表格 -->
    <div class="detail-table-section">
      <div class="table-container">
        <el-table
          :data="productDetailList"
          v-loading="detailLoading"
          border
          stripe
          style="width: 100%"
          height="250"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column
            prop="productCode"
            label="产品编号"
            width="180"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #header>
              <span class="required">*</span>产品编号
            </template>
            <template #default="scope">
              {{ scope.row.productCode || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="productName"
            label="产品名称"
            width="200"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #header>
              <span class="required">*</span>产品名称
            </template>
            <template #default="scope">
              {{ scope.row.productName || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="productSpec"
            label="产品规格"
            width="150"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.productSpec || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="unit"
            label="单位"
            width="100"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.unit || '个' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
            width="100"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #header>
              <span class="required">*</span>数量
            </template>
            <template #default="scope">
              {{ scope.row.quantity || 0 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="completedQty"
            label="完成数"
            width="100"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.completedQty || 0 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.creator || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            label="修改人"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ scope.row.modifier || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="modifyTime"
            label="修改时间"
            width="180"
            sortable
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.modifyTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

         <!-- 列设置对话框 -->
     <el-dialog
       v-model="columnSettingsVisible"
       title="列设置"
       width="600px"
       :close-on-click-modal="false"
     >
       <div class="column-settings">
         <div class="column-list">
           <div
             v-for="(column, index) in allColumns"
             :key="column.prop"
             class="column-item"
             :class="{ 'column-disabled': !column.visible }"
             draggable="true"
             @dragstart="handleDragStart($event, index)"
             @dragover="handleDragOver($event, index)"
             @drop="handleDrop($event, index)"
             @dragenter="handleDragEnter($event, index)"
             @dragleave="handleDragLeave($event, index)"
           >
             <el-checkbox
               v-model="column.visible"
               @change="handleColumnVisibilityChange"
             >
               {{ column.label }}
             </el-checkbox>
           </div>
         </div>
       </div>
       <template #footer>
         <span class="dialog-footer">
           <el-button @click="columnSettingsVisible = false">取消</el-button>
           <el-button type="primary" @click="handleColumnSettingsConfirm">
             确定
           </el-button>
         </span>
       </template>
     </el-dialog>

     <!-- 新建/编辑生产计划弹窗 -->
     <el-dialog
       v-model="dialogVisible"
       :title="dialogTitle"
       width="80%"
       :close-on-click-modal="false"
       class="production-plan-dialog"
     >
       <div class="dialog-content">
         <!-- 表单区域 -->
         <div class="form-section">
           <el-form :model="formData" label-width="100px">
             <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="单据编号:">
                   <el-input
                     v-model="formData.planNo"
                     placeholder="请输入,忽略将自动生成"
                     clearable
                   />
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="备注:">
                   <el-input
                     v-model="formData.remark"
                     type="textarea"
                     placeholder="备注"
                     :rows="3"
                   />
                 </el-form-item>
               </el-col>
             </el-row>
           </el-form>
         </div>

         <!-- 提示信息 -->
         <div class="hint-banner">
           <el-icon><Warning /></el-icon>
           <span>点击【数量】可以对订单数量直接进行修改</span>
         </div>

         <!-- 产品明细区域 -->
         <div class="product-detail-section">
           <div class="section-header">
             <h4>生产计划-产品明细</h4>
             <div class="section-actions">
               <el-button type="primary" @click="handleSelectProduct" size="small">
                 +选择产品
               </el-button>
               <el-button type="danger" @click="handleDeleteProductRow" size="small">
                 删除行
               </el-button>
               <el-button type="warning" @click="handleImportProduct" size="small">
                 导入
               </el-button>
               <el-button type="info" @click="handleRefreshProduct" size="small">
                 刷新
               </el-button>
             </div>
           </div>

                       <!-- 产品明细表格 -->
            <div class="table-container">
              <el-table
                :data="dialogProductDetailList"
                @selection-change="handleDialogProductSelectionChange"
                border
                stripe
                style="width: 100%"
                height="300"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column
                  prop="productCode"
                  label="产品编号"
                  width="180"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #header>
                    <span class="required">*</span>产品编号
                  </template>
                  <template #default="scope">
                    {{ scope.row.productCode || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="productName"
                  label="产品名称"
                  width="200"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #header>
                    <span class="required">*</span>产品名称
                  </template>
                  <template #default="scope">
                    {{ scope.row.productName || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="productSpec"
                  label="产品规格"
                  width="150"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.productSpec || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="workOrderNo"
                  label="工单编号"
                  width="180"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.workOrderNo || '待生成' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unit"
                  label="单位"
                  width="100"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.unit || '个' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="quantity"
                  label="数量"
                  width="100"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #header>
                    <span class="required">*</span>数量
                  </template>
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.quantity"
                      :min="0"
                      size="small"
                      style="width: 80px"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="completedQty"
                  label="完成数"
                  width="100"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.completedQty || 0 }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="创建时间"
                  width="180"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ formatDateTime(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="creator"
                  label="创建人"
                  width="120"
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.creator || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="modifier"
                  label="修改人"
                  width="120"
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ scope.row.modifier || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="modifyTime"
                  label="修改时间"
                  width="180"
                  sortable
                  show-overflow-tooltip
                  align="center"
                >
                  <template #default="scope">
                    {{ formatDateTime(scope.row.modifyTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>

           <!-- 分页 -->
           <div class="pagination-container">
             <el-pagination
               :current-page="1"
               :page-size="100"
               :page-sizes="[10, 20, 30, 50, 100]"
               :total="dialogProductDetailList.length"
               layout="total, sizes, prev, pager, next, jumper"
             />
           </div>
         </div>
       </div>

       <template #footer>
         <span class="dialog-footer">
           <el-button type="danger" @click="handleSave" :icon="Check">
             保存
           </el-button>
           <el-button type="primary" @click="handleClose" :icon="Close">
             关闭
           </el-button>
         </span>
               </template>
      </el-dialog>

      <!-- 产品选择弹窗 -->
      <el-dialog
        v-model="productSelectVisible"
        :title="productSelectTitle"
        width="80%"
        :close-on-click-modal="false"
        class="product-select-dialog"
      >
        <div class="dialog-content">
          <!-- 搜索区域 -->
          <div class="search-section">
            <el-form :model="productSearchForm" inline>
              <el-form-item label="产品编码:">
                <el-input
                  v-model="productSearchForm.productCode"
                  placeholder="请输入产品编码"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              <el-form-item label="产品名称:">
                <el-input
                  v-model="productSearchForm.productName"
                  placeholder="请输入产品名称"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              <el-form-item label="产品规格:">
                <el-input
                  v-model="productSearchForm.productSpec"
                  placeholder="请输入产品规格"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleProductSearch" :icon="Search">
                  搜索
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 产品列表表格 -->
          <div class="table-section">
            <el-table
              :data="productList"
              v-loading="productLoading"
              @selection-change="handleProductSelectionChange"
              border
              stripe
              style="width: 100%"
              height="400"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column
                prop="productCode"
                label="产品编号"
                width="250"
                sortable
                show-overflow-tooltip
                align="center"
              >
                <template #header>
                  <span>产品编号</span>
                  <el-icon class="sort-icon"><ArrowUp /></el-icon>
                </template>
              </el-table-column>
              <el-table-column
                prop="productName"
                label="产品名称"
                width="200"
                sortable
                show-overflow-tooltip
                align="center"
              >
                <template #header>
                  <span>产品名称</span>
                  <el-icon class="sort-icon"><ArrowUp /></el-icon>
                </template>
              </el-table-column>
              <el-table-column
                prop="inventoryUnit"
                label="库存单位"
                width="120"
                sortable
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                prop="productSpec"
                label="产品规格"
                width="150"
                sortable
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                prop="createTime"
                label="创建时间"
                width="180"
                sortable
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              :current-page="productPagination.pageIndex"
              :page-size="productPagination.pageSize"
              :page-sizes="[10, 20, 30, 50, 100]"
              :total="productPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="handleAddSelectedProducts">
              添加选择的数据
            </el-button>
            <el-button @click="handleCloseProductSelect">
              关闭
            </el-button>
          </span>
               </template>
     </el-dialog>

           <!-- 打印预览弹窗 -->
      <el-dialog
        v-model="printDialogVisible"
        title="打印预览 - 生产计划明细"
        width="90%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        class="print-preview-dialog"
      >
        <div class="print-preview-content">
          <!-- 打印预览头部 -->
          <div class="print-header">
            <div class="company-logo">
              <div class="logo-circle">IMES</div>
            </div>
            <div class="print-title">生产计划明细</div>
            <div class="qr-code">
              <div class="qr-placeholder">二维码</div>
            </div>
          </div>

          <!-- 生产计划信息 -->
          <div class="plan-info" v-if="printData && printData.length > 0">
            <div v-for="(plan, index) in printData" :key="index" class="plan-section">
              <div class="plan-header" v-if="printData.length > 1">
                <h4>生产计划 {{ index + 1 }}</h4>
              </div>
              <div class="info-row">
                <span class="info-label">单据编号:</span>
                <span class="info-value">{{ plan.planNo }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">制单人:</span>
                <span class="info-value">{{ plan.creator }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">创建时间:</span>
                <span class="info-value">{{ formatDateTime(plan.createTime) }}</span>
              </div>
              <div class="info-row" v-if="plan.remark">
                <span class="info-label">备注:</span>
                <span class="info-value">{{ plan.remark }}</span>
              </div>
              <div class="plan-divider" v-if="index < printData.length - 1"></div>
            </div>
          </div>

          <!-- 产品明细表格 -->
          <div class="product-detail-table" v-if="printProductDetails.length > 0">
            <table class="print-table">
              <thead>
                <tr>
                  <th>产品编号</th>
                  <th>产品名称</th>
                  <th>产品规格</th>
                  <th>工单编号</th>
                  <th>数量</th>
                  <th>完成数</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in printProductDetails" :key="index">
                  <td>{{ item.productCode }}</td>
                  <td>{{ item.productName }}</td>
                  <td>{{ item.productSpec || '-' }}</td>
                  <td>{{ item.workOrderNo || '-' }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>{{ item.completedQty || 0 }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 打印说明 -->
          <div class="print-footer">
            <p>打印时间: {{ formatDateTime(new Date().toISOString()) }}</p>
          </div>
        </div>

        <!-- 弹窗底部按钮 -->
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handlePrintPreview">
              <el-icon><Upload /></el-icon>
              打印预览
            </el-button>
            <el-button type="success" @click="handlePrintExecute">
              <el-icon><Upload /></el-icon>
              执行打印
            </el-button>
            <el-button @click="handleClosePrintDialog">
              <el-icon><Close /></el-icon>
              关闭
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 导入产品明细弹窗 -->
      <el-dialog
        v-model="importDialogVisible"
        title="生产计划-产品明细-导入"
        width="600px"
        :close-on-click-modal="false"
        class="import-dialog"
      >
       <div class="import-content">
         <!-- 操作按钮区域 -->
         <div class="import-actions">
           <el-button @click="handleSelectFile" :icon="Upload">
             选择文件
           </el-button>
           <el-button type="primary" @click="handleDownloadTemplate" :icon="Download">
             下载模板
           </el-button>
           <el-button type="success" @click="handleUploadFile" :icon="Upload" :disabled="!selectedFile">
             上传文件
           </el-button>
         </div>

         <!-- 上传说明 -->
         <div class="upload-notice">
           <el-icon><Warning /></el-icon>
           <div class="notice-content">
             <span class="notice-title">上传说明</span>
             <span class="notice-text">只能上传excel文件,文件大小不超过100M</span>
           </div>
         </div>

         <!-- 文件选择区域 -->
         <div class="file-drop-zone" @click="handleSelectFile" @drop="handleFileDrop" @dragover="handleFileDragOver" @dragleave="handleFileDragLeave">
           <div v-if="!selectedFile" class="drop-placeholder">
             <el-icon class="upload-icon"><Upload /></el-icon>
             <p>点击选择文件或拖拽文件到此处</p>
           </div>
           <div v-else class="selected-file">
             <el-icon class="file-icon"><Document /></el-icon>
             <span class="file-name">{{ selectedFile.name }}</span>
             <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
           </div>
         </div>
       </div>

       <template #footer>
         <span class="dialog-footer">
           <el-button @click="handleCloseImport">关闭</el-button>
         </span>
               </template>
      </el-dialog>

      <!-- 导出选项弹窗 -->
      <el-dialog
        v-model="exportDialogVisible"
        title="导出选项"
        width="500px"
        :close-on-click-modal="false"
        class="export-dialog"
      >
        <div class="export-content">
          <el-form :model="exportOptions" label-width="120px">
            <el-form-item label="导出类型:">
              <el-radio-group v-model="exportOptions.exportType">
                <el-radio label="main">仅生产计划</el-radio>
                <el-radio label="detail">仅产品明细</el-radio>
                <el-radio label="both">生产计划+产品明细</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="文件名:">
              <el-input
                v-model="exportOptions.fileName"
                placeholder="请输入文件名"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="包含表头:">
              <el-switch v-model="exportOptions.includeHeaders" />
            </el-form-item>
          </el-form>
          
          <div class="export-preview">
            <h4>导出预览:</h4>
            <div class="preview-info">
              <p v-if="exportOptions.exportType === 'main'">
                将导出 {{ productionPlanList.length }} 条生产计划数据
              </p>
              <p v-else-if="exportOptions.exportType === 'detail'">
                将导出 {{ productDetailList.length }} 条产品明细数据
              </p>
              <p v-else-if="exportOptions.exportType === 'both'">
                将导出 {{ productionPlanList.length }} 条生产计划数据 + {{ productDetailList.length }} 条产品明细数据
              </p>
            </div>
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeExportDialog">取消</el-button>
            <el-button type="primary" @click="executeExport" :icon="Download">
              开始导出
            </el-button>
          </span>
        </template>
      </el-dialog>
     </div>
   </template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Printer,
  Document,
  Delete,
  Download,
  Grid as GridIcon,
  Check,
  Close,
  Warning,
  ArrowUp,
  Upload
} from '@element-plus/icons-vue'
import { MES_SMH_ApiHost } from '../../utils/Interceptors'
import axios from 'axios'

// 接口定义
interface ProductionPlan {
  productionPlanId: number
  planNo: string
  remark: string
  createTime: string
  creator: string
  modifyTime: string
  modifier: string
}

interface ProductDetail {
  productionPlanDetailId: number
  productionPlanId: number
  workOrderId: number
  productCode: string
  productName: string
  productSpec: string
  workOrderNo: string
  unit: string
  quantity: number
  completedQty: number
  createTime: string
  creator: string
  modifyTime: string
  modifier: string
}

interface QueryForm {
  planNo: string
  pageIndex: number
  pageSize: number
}

interface Pagination {
  pageIndex: number
  pageSize: number
  totalCount: number
  totalPage: number
}

interface ColumnConfig {
  prop: string
  label: string
  width?: number
  sortable?: boolean
  visible: boolean
}

// 响应式数据
const loading = ref(false)
const detailLoading = ref(false)
const productionPlanList = ref<ProductionPlan[]>([])
const productDetailList = ref<ProductDetail[]>([])
const selectedRows = ref<ProductionPlan[]>([])
const selectedProductionPlan = ref<ProductionPlan | null>(null)
const columnSettingsVisible = ref(false)

// 弹窗相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const formData = reactive({
  planNo: '',
  remark: ''
})

// 弹窗中的产品明细数据
const dialogProductDetailList = ref<ProductDetail[]>([])
const dialogSelectedProductRows = ref<ProductDetail[]>([])

// 产品选择弹窗相关数据
const productSelectVisible = ref(false)
const productSelectTitle = ref('选择产品')
const productList = ref<any[]>([])
const selectedProducts = ref<any[]>([])
const productLoading = ref(false)

// 产品搜索表单
const productSearchForm = reactive({
  productCode: '',
  productName: '',
  productSpec: ''
})

// 产品分页信息
const productPagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0,
  totalPage: 0
})

// 导入相关数据
const importDialogVisible = ref(false)
const selectedFile = ref<File | null>(null)

// 打印相关数据
const printDialogVisible = ref(false)
const printData = ref<any>(null)
const printProductDetails = ref<any[]>([])

// 导出相关数据
const exportDialogVisible = ref(false)
const exportOptions = reactive({
  exportType: 'main', // 'main' | 'detail' | 'both'
  includeHeaders: true,
  fileName: ''
})

// 查询表单
const queryForm = reactive<QueryForm>({
  planNo: '',
  pageIndex: 1,
  pageSize: 30
})

// 分页信息
const pagination = reactive<Pagination>({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0,
  totalPage: 0
})

// 列配置
const allColumns = ref<ColumnConfig[]>([
  { prop: 'planNo', label: '单据编号', width: 220, sortable: true, visible: true },
  { prop: 'remark', label: '备注', width: 200, sortable: false, visible: true },
  { prop: 'createTime', label: '创建时间', width: 180, sortable: true, visible: true },
  { prop: 'creator', label: '创建人', width: 120, sortable: false, visible: true },
  { prop: 'modifier', label: '修改人', width: 120, sortable: false, visible: true },
  { prop: 'modifyTime', label: '修改时间', width: 180, sortable: true, visible: true }
])

// 计算属性
const visibleColumns = computed(() => {
  return allColumns.value.filter(col => col.visible)
})

// 获取生产计划列表
const getProductionPlanList = async () => {
  try {
    loading.value = true
    const response = await MES_SMH_ApiHost.post('/api/ProductionPlan/GetPagedList', {
      planNo: queryForm.planNo || '',
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    })

    console.log('完整API响应:', response) // 调试日志
    console.log('响应数据:', response.data) // 调试日志

    // 根据Swagger截图，响应结构应该是 { code: 200, data: { totalCount, totalPage, pageData } }
    if (response.data && response.data.code === 200) {
      const data = response.data.data || response.data
      productionPlanList.value = data.pageData || []
      pagination.totalCount = data.totalCount || 0
      pagination.totalPage = data.totalPage || 0
      console.log('解析后的数据:', {
        list: productionPlanList.value,
        totalCount: pagination.totalCount,
        totalPage: pagination.totalPage
      })
    } else {
      ElMessage.error(response.data?.msg || '获取生产计划列表失败')
      productionPlanList.value = []
      pagination.totalCount = 0
      pagination.totalPage = 0
    }
  } catch (error) {
    console.error('获取生产计划列表失败:', error)
    ElMessage.error('获取生产计划列表失败')
    productionPlanList.value = []
    pagination.totalCount = 0
    pagination.totalPage = 0
  } finally {
    loading.value = false
  }
}

// 获取产品明细列表
const getProductDetailList = async (productionPlanId: number) => {
  try {
    detailLoading.value = true
    const response = await MES_SMH_ApiHost.get(`/api/ProductionPlan/GetProductDetails/${productionPlanId}`)

    console.log('产品明细API响应:', response.data) // 调试日志

    if (response.data.code === 200) {
      productDetailList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '获取产品明细失败')
      productDetailList.value = []
    }
  } catch (error) {
    console.error('获取产品明细失败:', error)
    ElMessage.error('获取产品明细失败')
    productDetailList.value = []
  } finally {
    detailLoading.value = false
  }
}

// 获取编辑时的产品明细列表
const getEditProductDetails = async (productionPlanId: number) => {
  try {
    const response = await MES_SMH_ApiHost.get(`/api/ProductionPlan/GetProductDetails/${productionPlanId}`)

    console.log('编辑产品明细API响应:', response.data) // 调试日志

    if (response.data.code === 200) {
      dialogProductDetailList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '获取产品明细失败')
      dialogProductDetailList.value = []
    }
  } catch (error) {
    console.error('获取编辑产品明细失败:', error)
    ElMessage.error('获取产品明细失败')
    dialogProductDetailList.value = []
  }
}

// 查询
const handleQuery = () => {
  pagination.pageIndex = 1
  getProductionPlanList()
}

// 新建
const handleNew = () => {
  dialogVisible.value = true
  dialogTitle.value = '生产计划(新建)'
  isEdit.value = false
  resetForm()
}

// 编辑单个生产计划
const handleEditSingle = (row: ProductionPlan) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑生产计划'
  isEdit.value = true
  
  // 设置选中的行
  selectedRows.value = [row]
  
  // 回填表单数据
  formData.planNo = row.planNo
  formData.remark = row.remark || ''
  
  // 获取产品明细数据
  getEditProductDetails(row.productionPlanId)
}

// 编辑（批量选择）
const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  
  const selectedPlan = selectedRows.value[0]
  dialogVisible.value = true
  dialogTitle.value = '编辑'
  isEdit.value = true
  
  // 回填表单数据
  formData.planNo = selectedPlan.planNo
  formData.remark = selectedPlan.remark || ''
  
  // 获取产品明细数据
  getEditProductDetails(selectedPlan.productionPlanId)
}

// 打印生产计划
const handlePrint = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要打印的生产计划')
    return
  }

  try {
    // 支持打印多条数据
    const selectedPlans = selectedRows.value
    const printPlans = []
    const allProductDetails = []

    // 获取所有选中计划的详细信息
    for (const plan of selectedPlans) {
      const productionPlanId = plan.productionPlanId
      
      try {
        // 获取生产计划详情
        const planResponse = await MES_SMH_ApiHost.get(`/api/ProductionPlan/GetDetail/${productionPlanId}`)
        if (planResponse.data.code === 200) {
          printPlans.push(planResponse.data.data)
        }

        // 获取产品明细
        const detailResponse = await MES_SMH_ApiHost.get(`/api/ProductionPlan/GetProductDetails/${productionPlanId}`)
        if (detailResponse.data.code === 200) {
          const details = detailResponse.data.data || []
          allProductDetails.push(...details)
        }
      } catch (error) {
        console.error(`获取生产计划 ${productionPlanId} 信息失败:`, error)
        // 如果API调用失败，使用当前行的数据作为备选
        printPlans.push(plan)
      }
    }

    if (printPlans.length === 0) {
      ElMessage.error('没有获取到有效的生产计划信息')
      return
    }

    // 设置打印数据
    printData.value = printPlans
    printProductDetails.value = allProductDetails
    printDialogVisible.value = true

    ElMessage.success(`准备打印 ${printPlans.length} 个生产计划`)

  } catch (error) {
    console.error('打印准备失败:', error)
    ElMessage.error('打印准备失败，请重试')
  }
}

// 打印预览
const handlePrintPreview = () => {
  // 打开浏览器打印预览
  window.print()
}

// 执行打印
const handlePrintExecute = () => {
  // 执行打印
  window.print()
}

// 关闭打印对话框
const handleClosePrintDialog = () => {
  printDialogVisible.value = false
  printData.value = null
  printProductDetails.value = []
}

// 模版Excel导出
const handleExportTemplate = () => {
  ElMessage.info('模版Excel导出功能待实现')
}

// 删除单个生产计划
const handleDeleteSingle = async (productionPlanId: number, planNo: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除生产计划 "${planNo}" 吗？\n删除后将无法恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const loadingInstance = ElMessage({
      message: '正在删除中...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    try {
      const response = await MES_SMH_ApiHost.delete(`/api/ProductionPlan/Delete/${productionPlanId}`)
      loadingInstance.close()

      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        getProductionPlanList()
        
        // 如果当前选中的生产计划被删除，清空产品明细
        if (selectedProductionPlan.value && selectedProductionPlan.value.productionPlanId === productionPlanId) {
          productDetailList.value = []
          selectedProductionPlan.value = null
        }
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (apiError: any) {
      loadingInstance.close()
      console.error('删除API调用失败:', apiError)
      ElMessage.error(`删除失败: ${apiError.response?.data?.msg || apiError.message || '网络错误'}`)
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除操作失败:', error)
    ElMessage.error('删除操作失败，请重试')
  }
}

// 删除生产计划（批量）
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的生产计划')
    return
  }

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个生产计划吗？\n删除后将无法恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )

    // 显示加载状态
    const loadingInstance = ElMessage({
      message: '正在删除中...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    try {
      const productionPlanIds = selectedRows.value.map(row => row.productionPlanId)
      const response = await MES_SMH_ApiHost.delete('/api/ProductionPlan/BatchDelete', { data: { productionPlanIds } })

      // 关闭加载提示
      loadingInstance.close()

      if (response.data.code === 200) {
        const result = response.data.data
        const successCount = result.successCount || 0
        const failCount = result.failCount || 0
        const failReasons = result.failReasons || []

        // 根据删除结果显示不同的消息
        if (successCount > 0 && failCount === 0) {
          // 全部删除成功
          ElMessage.success(`删除成功！成功删除 ${successCount} 个生产计划`)
        } else if (successCount > 0 && failCount > 0) {
          // 部分删除成功
          ElMessage.warning(`部分删除成功！成功：${successCount} 个，失败：${failCount} 个`)
          
          // 如果有失败原因，显示详细信息
          if (failReasons.length > 0) {
            console.warn('删除失败详情:', failReasons)
            // 可以选择显示失败原因弹窗
            setTimeout(() => {
              ElMessageBox.alert(
                `删除失败的生产计划：\n${failReasons.join('\n')}`,
                '删除失败详情',
                {
                  confirmButtonText: '确定',
                  type: 'warning'
                }
              )
            }, 1000)
          }
        } else {
          // 全部删除失败
          ElMessage.error(`删除失败！失败：${failCount} 个`)
          if (failReasons.length > 0) {
            console.error('删除失败详情:', failReasons)
          }
        }

        // 刷新列表
        getProductionPlanList()
        
        // 如果当前选中的生产计划被删除，清空产品明细
        if (selectedProductionPlan.value && productionPlanIds.includes(selectedProductionPlan.value.productionPlanId)) {
          productDetailList.value = []
          selectedProductionPlan.value = null
        }
        
        // 清空选择
        selectedRows.value = []
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (apiError: any) {
      // 关闭加载提示
      loadingInstance.close()
      
      console.error('删除API调用失败:', apiError)
      ElMessage.error(`删除失败: ${apiError.response?.data?.msg || apiError.message || '网络错误'}`)
    }
  } catch (error) {
    // 用户取消删除
    if (error === 'cancel') {
      return
    }
    
    console.error('删除操作失败:', error)
    ElMessage.error('删除操作失败，请重试')
  }
}

// 导出生产计划
const handleExport = () => {
  // 设置默认文件名
  exportOptions.fileName = `生产计划数据_${new Date().toISOString().slice(0, 10)}`
  exportDialogVisible.value = true
}

// 执行导出
const executeExport = async () => {
  try {
    let exportData: any[] = []
    let fileName = exportOptions.fileName || `生产计划数据_${new Date().toISOString().slice(0, 10)}`

    if (exportOptions.exportType === 'main' || exportOptions.exportType === 'both') {
      // 导出生产计划主表数据
      const mainData = productionPlanList.value.map((item, index) => ({
        '序号': index + 1,
        '单据编号': item.planNo || '',
        '备注': item.remark || '',
        '创建时间': formatExportDateTime(item.createTime),
        '创建人': item.creator || '',
        '修改人': item.modifier || '',
        '修改时间': formatExportDateTime(item.modifyTime)
      }))
      exportData.push(...mainData)
    }

    if (exportOptions.exportType === 'detail' || exportOptions.exportType === 'both') {
      // 导出产品明细数据
      const detailData = productDetailList.value.map((item, index) => ({
        '序号': index + 1,
        '产品编号': item.productCode || '',
        '产品名称': item.productName || '',
        '产品规格': item.productSpec || '',
        '工单编号': item.workOrderNo || '',
        '单位': item.unit || '',
        '数量': item.quantity || 0,
        '完成数': item.completedQty || 0,
        '创建时间': formatExportDateTime(item.createTime),
        '创建人': item.creator || '',
        '修改人': item.modifier || '',
        '修改时间': formatExportDateTime(item.modifyTime)
      }))
      exportData.push(...detailData)
    }

    // 如果没有数据，提示用户
    if (exportData.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    // 确定表头
    let headers: string[] = []
    if (exportOptions.exportType === 'main') {
      headers = ['序号', '单据编号', '备注', '创建时间', '创建人', '修改人', '修改时间']
    } else if (exportOptions.exportType === 'detail') {
      headers = ['序号', '产品编号', '产品名称', '产品规格', '工单编号', '单位', '数量', '完成数', '创建时间', '创建人', '修改人', '修改时间']
    } else if (exportOptions.exportType === 'both') {
      headers = ['序号', '单据编号', '备注', '创建时间', '创建人', '修改人', '修改时间', '产品编号', '产品名称', '产品规格', '工单编号', '单位', '数量', '完成数']
    }

    // 创建CSV内容
    const csvContent = [
      exportOptions.includeHeaders ? headers.join(',') : '',
      ...exportData.map(row => 
        headers.map(header => {
          const value = (row as any)[header] || ''
          // 确保值是字符串类型
          const stringValue = String(value)
          // 如果值包含逗号、引号或换行符，需要用引号包围
          if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
            return `"${stringValue.replace(/"/g, '""')}"`
          }
          return stringValue
        }).join(',')
      )
    ].filter(line => line).join('\n')

    // 添加BOM以确保Excel正确识别中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `${fileName}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success(`成功导出 ${exportData.length} 条数据`)
    exportDialogVisible.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 格式化导出时间（专门用于导出功能）
const formatExportDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    return dateTimeStr
  }
}

// 关闭导出对话框
const closeExportDialog = () => {
  exportDialogVisible.value = false
}

// 列设置
const handleColumnSettings = () => {
  columnSettingsVisible.value = true
}

// 列可见性变化
const handleColumnVisibilityChange = () => {
  // 列可见性变化处理
}

// 列设置确认
const handleColumnSettingsConfirm = () => {
  columnSettingsVisible.value = false
  ElMessage.success('列设置已保存')
}

// 表格选择变化
const handleSelectionChange = (selection: ProductionPlan[]) => {
  selectedRows.value = selection
}

// 行点击
const handleRowClick = (row: ProductionPlan) => {
  selectedProductionPlan.value = row
  getProductDetailList(row.productionPlanId)
}

// 获取行类名
const getRowClassName = ({ row }: { row: ProductionPlan }) => {
  if (selectedProductionPlan.value && row.productionPlanId === selectedProductionPlan.value.productionPlanId) {
    return 'selected-row'
  }
  return ''
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  getProductionPlanList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  getProductionPlanList()
}

// 拖拽相关
const dragIndex = ref(-1)

const handleDragStart = (event: DragEvent, index: number) => {
  dragIndex.value = index
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
  }
}

const handleDragOver = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
}

const handleDrop = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (dragIndex.value !== -1 && dragIndex.value !== index) {
    const draggedItem = allColumns.value[dragIndex.value]
    allColumns.value.splice(dragIndex.value, 1)
    allColumns.value.splice(index, 0, draggedItem)
    dragIndex.value = -1
  }
}

const handleDragEnter = (event: DragEvent, index: number) => {
  event.preventDefault()
  const target = event.currentTarget as HTMLElement
  target.classList.add('drag-over')
}

const handleDragLeave = (event: DragEvent, index: number) => {
  const target = event.currentTarget as HTMLElement
  target.classList.remove('drag-over')
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '-'
  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    return dateTimeStr
  }
}

// 重置表单
const resetForm = () => {
  formData.planNo = ''
  formData.remark = ''
  dialogProductDetailList.value = []
  dialogSelectedProductRows.value = []
  isEdit.value = false
}

// 保存生产计划
const handleSave = async () => {
  try {
    // 验证产品明细数据
    if (!dialogProductDetailList.value || dialogProductDetailList.value.length === 0) {
      ElMessage.warning('请至少添加一个产品明细')
      return
    }

    // 验证必填字段
    for (let i = 0; i < dialogProductDetailList.value.length; i++) {
      const detail = dialogProductDetailList.value[i]
      if (!detail.productCode || !detail.productName || !detail.quantity || detail.quantity <= 0) {
        ElMessage.warning(`第${i + 1}行产品明细数据不完整，请检查产品编号、产品名称和数量`)
        return
      }
    }

    if (isEdit.value) {
      // 编辑模式
      const selectedPlan = selectedRows.value[0]
      // 使用 PascalCase 属性，兼容后端严格大小写绑定
      const editDto = {
        ProductionPlanId: Number(selectedPlan.productionPlanId),
        PlanNo: formData.planNo,
        Remark: formData.remark,
        ProductDetails: dialogProductDetailList.value.map(detail => ({
          ProductionPlanDetailId: (() => {
            const idNum = Number(detail.productionPlanDetailId)
            return Number.isInteger(idNum) && idNum > 0 && idNum < 2147483647 ? idNum : 0
          })(),
          ProductCode: detail.productCode,
          ProductName: detail.productName,
          ProductSpec: detail.productSpec || '',
          WorkOrderNo: detail.workOrderNo || '',
          Quantity: Number(detail.quantity) || 0,
          CompletedQty: Number(detail.completedQty) || 0
        }))
      }
      
      console.log('编辑请求数据:', editDto) // 调试日志
      
      // 后端期望请求体直接为 DTO 本身（与 Swagger 示例一致）
      const response = await MES_SMH_ApiHost.put('/api/ProductionPlan/Edit', editDto)
      
      console.log('编辑响应:', response.data) // 调试日志
      
      if (response.data.code === 200) {
        ElMessage.success('编辑成功')
        dialogVisible.value = false
        getProductionPlanList()
        // 如果当前选中的生产计划被编辑，刷新产品明细
        if (selectedProductionPlan.value && selectedProductionPlan.value.productionPlanId === selectedPlan.productionPlanId) {
          getProductDetailList(selectedPlan.productionPlanId)
        }
      } else {
        ElMessage.error(response.data.msg || '编辑失败')
      }
    } else {
      // 新建模式
      const requestData = {
        planNo: formData.planNo,
        remark: formData.remark,
        productDetails: dialogProductDetailList.value.map(detail => ({
          productCode: detail.productCode,
          productName: detail.productName,
          productSpec: detail.productSpec || '',
          workOrderNo: detail.workOrderNo || '',
          quantity: detail.quantity,
          completedQty: detail.completedQty || 0
        }))
      }
      
      console.log('新建请求数据:', requestData) // 调试日志
      
      const response = await MES_SMH_ApiHost.post('/api/ProductionPlan/Add', requestData)
      
      console.log('新建响应:', response.data) // 调试日志
      
      if (response.data.code === 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getProductionPlanList()
      } else {
        ElMessage.error(response.data.msg || '保存失败')
      }
    }
  } catch (error: any) {
    console.error('保存失败:', error)
    console.error('错误详情:', error.response?.data) // 调试日志
    ElMessage.error(`保存失败: ${error.response?.data?.msg || error.message}`)
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 选择产品
const handleSelectProduct = () => {
  productSelectVisible.value = true
  productSelectTitle.value = '选择产品'
  getProductList()
}

// 获取产品列表
const getProductList = async () => {
  try {
    productLoading.value = true
    
    // 调用后端API获取产品数据
    const response = await MES_SMH_ApiHost.get('/api/ProductionPlan/GetAllProductDetails', {
      params: {
        productCode: productSearchForm.productCode || undefined,
        productName: productSearchForm.productName || undefined,
        productSpec: productSearchForm.productSpec || undefined
      }
    })

    if (response.data.code === 200) {
      const data = response.data.data || []
      const products = data.map((item: any) => ({
        productId: item.productionPlanDetailId, // 使用产品ID作为临时ID
        productCode: item.productCode,
        productName: item.productName,
        productSpec: item.productSpec,
        inventoryUnit: item.unit || '个', // 使用后端的库存单位，默认为'个'
        stockQty: item.stockQty || 0, // 库存数量
        price: item.price || 0, // 单价
        createTime: item.createTime
      }))
      productList.value = products
      productPagination.totalCount = products.length
      productPagination.totalPage = Math.ceil(products.length / productPagination.pageSize)
      console.log('处理后的产品选择数据:', products)
    } else {
      ElMessage.error(response.data.msg || '获取产品列表失败')
    }
    
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    productLoading.value = false
  }
}

// 产品搜索
const handleProductSearch = () => {
  productPagination.pageIndex = 1
  getProductList()
}

// 产品表格选择变化
const handleProductSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection
}

// 添加选择的产品
const handleAddSelectedProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要添加的产品')
    return
  }
  
  // 将选中的产品添加到生产计划的产品明细中
  selectedProducts.value.forEach(product => {
    const newProductDetail: ProductDetail = {
      // 新增明细在后端为 Nullable<int>，这里统一用 0 表示新建
      productionPlanDetailId: 0,
      productionPlanId: 0,
      workOrderId: Math.floor(Math.random() * 1000) + 1,
      productCode: product.productCode,
      productName: product.productName,
      productSpec: product.productSpec,
      workOrderNo: `WO${Date.now()}${Math.floor(Math.random() * 1000)}`,
      unit: product.inventoryUnit,
      quantity: 1, // 默认数量为1
      completedQty: 0,
      createTime: new Date().toISOString(),
      creator: '当前用户',
      modifyTime: new Date().toISOString(),
      modifier: '当前用户'
    }
    dialogProductDetailList.value.push(newProductDetail)
  })
  
  ElMessage.success(`成功添加 ${selectedProducts.value.length} 个产品`)
  productSelectVisible.value = false
  selectedProducts.value = []
}

// 关闭产品选择弹窗
const handleCloseProductSelect = () => {
  productSelectVisible.value = false
  selectedProducts.value = []
}

// 删除产品行
const handleDeleteProductRow = () => {
  if (dialogSelectedProductRows.value.length === 0) {
    ElMessage.warning('请选择要删除的产品')
    return
  }
  
  const selectedIds = dialogSelectedProductRows.value.map(row => row.productionPlanDetailId)
  dialogProductDetailList.value = dialogProductDetailList.value.filter(
    item => !selectedIds.includes(item.productionPlanDetailId)
  )
  dialogSelectedProductRows.value = []
  ElMessage.success('删除成功')
}

// 导入产品
const handleImportProduct = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

// 导入相关函数
const handleSelectFile = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = (event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
      const file = target.files[0]
      if (file.size > 100 * 1024 * 1024) { // 100MB
        ElMessage.error('文件大小不能超过100M')
        return
      }
      if (!file.name.match(/\.(xlsx|xls)$/i)) {
        ElMessage.error('只能上传Excel文件')
        return
      }
      selectedFile.value = file
    }
  }
  input.click()
}

const handleDownloadTemplate = () => {
  // 创建Excel模板数据 - 根据图二的列头
  const templateData = [
    ['产品编号', '产品名称', '产品规格', '工单编号', '数量', '完成数'],
    ['CP001', '示例产品1', '规格A', 'WO20231201001', '10', '0'],
    ['CP002', '示例产品2', '规格B', 'WO20231201002', '20', '0'],
    ['CP003', '示例产品3', '规格C', 'WO20231201003', '15', '0']
  ]
  
  // 生成CSV格式的数据
  const csvContent = templateData.map(row => row.join(',')).join('\n')
  
  // 添加BOM以确保Excel正确识别中文
  const BOM = '\uFEFF'
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
  
  // 创建下载链接
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '生产计划产品明细导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('模板下载成功')
}

const handleUploadFile = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  try {
    // 读取文件内容
    const reader = new FileReader()
    reader.onload = (event) => {
      const content = event.target?.result as string
      if (content) {
        // 解析CSV内容
        const lines = content.split('\n')
        const importedProducts: any[] = []
        
        // 跳过标题行，从第二行开始处理数据
        for (let i = 1; i < lines.length; i++) {
          const line = lines[i].trim()
          if (line) {
            const columns = line.split(',')
            if (columns.length >= 6) {
              const product = {
                productCode: columns[0]?.trim() || '',
                productName: columns[1]?.trim() || '',
                productSpec: columns[2]?.trim() || '',
                workOrderNo: columns[3]?.trim() || '',
                quantity: parseInt(columns[4]?.trim()) || 0,
                completedQty: parseInt(columns[5]?.trim()) || 0
              }
              
              // 验证必填字段
              if (product.productCode && product.productName && product.quantity > 0) {
                importedProducts.push(product)
              }
            }
          }
        }
        
        if (importedProducts.length > 0) {
          // 将导入的产品添加到弹窗中的产品明细列表
          importedProducts.forEach(product => {
            const newProductDetail = {
              // 新增明细在后端为 Nullable<int>，这里统一用 0 表示新建
              productionPlanDetailId: 0,
              productionPlanId: 0,
              workOrderId: Math.floor(Math.random() * 1000) + 1,
              productCode: product.productCode,
              productName: product.productName,
              productSpec: product.productSpec,
              workOrderNo: product.workOrderNo,
              unit: '个', // 默认单位
              quantity: product.quantity,
              completedQty: product.completedQty,
              createTime: new Date().toISOString(),
              creator: '当前用户',
              modifyTime: new Date().toISOString(),
              modifier: '当前用户'
            }
            dialogProductDetailList.value.push(newProductDetail)
          })
          
          ElMessage.success(`成功导入 ${importedProducts.length} 个产品`)
          importDialogVisible.value = false
          selectedFile.value = null
        } else {
          ElMessage.warning('文件中没有有效的数据，请检查文件格式')
        }
      }
    }
    
    reader.onerror = () => {
      ElMessage.error('文件读取失败')
    }
    
    // 读取文件内容
    reader.readAsText(selectedFile.value, 'utf-8')
    
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
  }
}

const handleFileDrop = (event: DragEvent) => {
  event.preventDefault()
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    const file = files[0]
    if (file.size > 100 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过100M')
      return
    }
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
      ElMessage.error('只能上传Excel文件')
      return
    }
    selectedFile.value = file
  }
}

const handleFileDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleFileDragLeave = (event: DragEvent) => {
  event.preventDefault()
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleCloseImport = () => {
  importDialogVisible.value = false
  selectedFile.value = null
}

// 刷新产品列表
const handleRefreshProduct = () => {
  ElMessage.info('刷新产品列表功能待实现')
}

// 弹窗中产品明细表格选择变化
const handleDialogProductSelectionChange = (selection: ProductDetail[]) => {
  dialogSelectedProductRows.value = selection
}

// 初始化
onMounted(() => {
  getProductionPlanList()
})
</script>

<style scoped>
.production-plan-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部区域样式 */
.top-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e4e7ed;
}

.title-area h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.search-area {
  display: flex;
  align-items: center;
}

.action-area {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-left: 20px;
}

/* 表格区域样式 */
.table-section {
  background: white;
  margin-bottom: 20px;
}

.table-container {
  overflow: hidden;
}

.pagination-section {
  padding: 15px 20px;
  text-align: right;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.detail-header {
  margin: 20px 0 10px 0;
}

.detail-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.detail-table-section {
  background: white;
}

.plan-no-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.plan-no-link:hover {
  color: #66b1ff;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

.selected-row {
  background-color: #f0f9ff !important;
}

.column-settings {
  max-height: 400px;
  overflow-y: auto;
}

.column-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.column-item {
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.column-item:hover {
  background-color: #f5f7fa;
}

.column-item.column-disabled {
  opacity: 0.6;
  background-color: #f5f7fa;
}

.column-item.drag-over {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式优化 - 强制滚动效果 */
.table-section .table-container :deep(.el-table) {
  border: 1px solid #e4e7ed;
}

.table-section .table-container :deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

.table-section .table-container :deep(.el-table td) {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.table-section .table-container :deep(.el-table--border) {
  border: 1px solid #e4e7ed;
}

.table-section .table-container :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

.table-section .table-container :deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

/* 生产计划表格行点击效果 */
.table-section .table-container :deep(.el-table__row) {
  cursor: pointer;
}

.table-section .table-container :deep(.el-table__row:hover) {
  background-color: #e6f7ff !important;
}

.table-section .table-container :deep(.el-table__row.current-row) {
  background-color: #e6f7ff !important;
}

/* 产品明细表格样式 */
.detail-table-section .table-container :deep(.el-table) {
  border: 1px solid #e4e7ed;
}

.detail-table-section .table-container :deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

.detail-table-section .table-container :deep(.el-table td) {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.detail-table-section .table-container :deep(.el-table--border) {
  border: 1px solid #e4e7ed;
}

.detail-table-section .table-container :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

.detail-table-section .table-container :deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

/* 表格行高设置 */
.table-section .table-container :deep(.el-table__body tr),
.detail-table-section .table-container :deep(.el-table__body tr) {
  height: 45px;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: flex-end;
  padding: 0;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

/* 按钮样式调整 */
:deep(.el-button) {
  padding: 8px 15px;
  font-size: 14px;
}

/* 表单样式调整 */
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 新建/编辑弹窗样式 */
.production-plan-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.dialog-content {
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.hint-banner {
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #d46b08;
  font-size: 14px;
}

.hint-banner .el-icon {
  font-size: 16px;
}

.product-detail-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-header h4 {
  color: #409eff;
  margin: 0;
  font-size: 16px;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  padding: 12px 16px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.pagination-container :deep(.el-pagination) {
  font-size: 12px;
  color: #595959;
}

.pagination-container :deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
}

.pagination-container :deep(.el-pagination .el-pager li.is-active) {
  background-color: #1890ff;
  color: white;
}

.pagination-container :deep(.el-pagination .btn-prev),
.pagination-container :deep(.el-pagination .btn-next) {
  border-radius: 4px;
  margin: 0 2px;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes) {
  margin-right: 16px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes .el-select) {
  width: 100px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes .el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  box-shadow: none;
}

.pagination-container :deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

.pagination-container :deep(.el-pagination .el-pagination__jump .el-input) {
  width: 50px;
  margin: 0 8px;
}

.pagination-container :deep(.el-pagination .el-pagination__jump .el-input .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  box-shadow: none;
}

/* 产品选择弹窗样式 */
.product-select-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.product-select-dialog .dialog-content {
  padding: 20px;
}

.product-select-dialog .search-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.product-select-dialog .table-section {
  margin-bottom: 20px;
}

.product-select-dialog .pagination-section {
  padding: 15px 0;
  text-align: center;
  border-top: 1px solid #eee;
}

.product-select-dialog .sort-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #c0c4cc;
}

.product-select-dialog :deep(.el-table) {
  border: 1px solid #e4e7ed;
}

.product-select-dialog :deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

.product-select-dialog :deep(.el-table td) {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.product-select-dialog :deep(.el-table--border) {
  border: 1px solid #e4e7ed;
}

.product-select-dialog :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

.product-select-dialog :deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

.product-select-dialog :deep(.el-table__body tr) {
  height: 45px;
}

.product-select-dialog :deep(.el-pagination) {
  justify-content: center;
  padding: 0;
}

.product-select-dialog :deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

/* 导入弹窗样式 */
.import-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.import-content {
  padding: 20px;
}

.import-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.upload-notice {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
}

.upload-notice .el-icon {
  color: #d46b08;
  font-size: 16px;
  margin-top: 2px;
}

.notice-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notice-title {
  font-weight: 600;
  color: #262626;
  font-size: 14px;
}

.notice-text {
  color: #8c8c8c;
  font-size: 12px;
}

.file-drop-zone {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.file-drop-zone:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.drop-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #8c8c8c;
}

.upload-icon {
  font-size: 48px;
  color: #d9d9d9;
}

.drop-placeholder p {
  margin: 0;
  font-size: 14px;
}

.selected-file {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #262626;
}

.file-icon {
  font-size: 24px;
  color: #52c41a;
}

.file-name {
  font-weight: 500;
  font-size: 14px;
}

.file-size {
  color: #8c8c8c;
  font-size: 12px;
}

/* 打印预览弹窗样式 */
.print-preview-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.print-preview-content {
  padding: 20px;
  background: white;
}

.print-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #333;
}

.company-logo {
  flex: 1;
}

.logo-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.print-title {
  flex: 2;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.qr-code {
  flex: 1;
  text-align: right;
}

.qr-placeholder {
  width: 60px;
  height: 60px;
  border: 2px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.plan-info {
  margin-bottom: 30px;
}

.plan-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.plan-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.plan-header h4 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  line-height: 1.5;
}

.info-label {
  width: 100px;
  font-weight: bold;
  color: #333;
}

.info-value {
  flex: 1;
  color: #666;
}

.plan-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 20px 0;
}

.product-detail-table {
  margin-bottom: 30px;
}

.print-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #333;
}

.print-table th,
.print-table td {
  border: 1px solid #333;
  padding: 8px 12px;
  text-align: center;
  font-size: 14px;
}

.print-table th {
  background: #f5f7fa;
  font-weight: bold;
  color: #333;
}

.print-table td {
  color: #666;
}

.print-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  color: #999;
  font-size: 12px;
}

/* 打印样式 */
@media print {
  .print-preview-dialog :deep(.el-dialog__header),
  .print-preview-dialog :deep(.el-dialog__footer) {
    display: none !important;
  }
  
  .print-preview-dialog :deep(.el-dialog) {
    position: static !important;
    margin: 0 !important;
    width: 100% !important;
    max-width: none !important;
  }
  
  .print-preview-dialog :deep(.el-dialog__body) {
    padding: 0 !important;
  }
  
  .print-preview-content {
    padding: 0 !important;
  }
  
  .print-header {
    margin-bottom: 20px !important;
  }
  
  .print-title {
    font-size: 20px !important;
  }
  
  .print-table th,
     .print-table td {
     font-size: 12px !important;
     padding: 6px 8px !important;
   }
 }

/* 导出弹窗样式 */
.export-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.export-content {
  max-height: 400px;
  overflow-y: auto;
}

.export-preview {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.export-preview h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.preview-info p {
  margin: 5px 0;
  color: #666;
  font-size: 13px;
}

.export-dialog :deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.export-dialog :deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 8px;
}

.export-dialog :deep(.el-form-item) {
  margin-bottom: 20px;
}

.export-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}
</style>
